#!/usr/bin/env pytho3
#-*- coding:utf-8 -*-

'''
文件名称：main.py
创 建 者：yang qiang
创建日期：2018年12月16日
描    述：
'''

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head or not head.next:
            return head

        fast = head
        slow = head

        while fast and fast.next:
            fast = fast.next.next
            pre = slow
            slow = slow.next

        pre.next = None
        
        left = self.sortList(head)
        right = self.sortList(slow)

        return self.merge(left, right)

    
    def merge(self, left, right):
        newhead = ListNode(0)
        p = newhead 
        while left and right:
            if left.val < right.val:
                p.next = left
                p = p.next
                left = left.next
            else:
                p.next = right
                p = p.next
                right = right.next

        p.next = left if left else right
        return newhead.next
